package com.dzz.sjgl.utils;

import com.lowagie.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @author KRIC
 */
public class Pdf2Image {
    private static Logger logger = LoggerFactory.getLogger(Pdf2Image.class);

    /***
     * PDF文件转PNG图片，全部页数
     *
     * @param pdfFilePath pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰，相对转换速度越慢
     */
    public static String pdf2Image(String pdfFilePath, String dstImgFolder, int dpi, int maxPage) throws Exception {
        File file = new File(pdfFilePath);
        PDDocument pdDocument;
        String imgPDFPath = file.getParent();
        int dot = file.getName().lastIndexOf('.');
        // 获取图片文件名
        String imagePDFName = file.getName().substring(0, dot);
        String imgFolderPath;
        if ("".equals(dstImgFolder)) {
            // 获取图片存放的文件夹路径
            imgFolderPath = imgPDFPath + "\\" + imagePDFName;
        } else {
            imgFolderPath = dstImgFolder + "\\" + imagePDFName;
        }

        if (createDirectory(imgFolderPath)) {

            pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            /* dpi越大转换后越清晰，相对转换速度越慢 */
            PdfReader reader = new PdfReader(pdfFilePath);
            int pages = reader.getNumberOfPages();
            if (maxPage < pages) {
                pages = maxPage;
            }
            StringBuffer imgFilePath;
            for (int i = 0; i < pages; i++) {
                String imgFilePathPrefix = imgFolderPath + "\\" + imagePDFName;
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                imgFilePath.append("_");
                imgFilePath.append(i + 1);
                imgFilePath.append(".png");
                File dstFile = new File(imgFilePath.toString());
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(image, "png", dstFile);
            }
            logger.info("PDF文档转PNG图片成功！");
            pdDocument.close();
            reader.close();
        } else {
            throw new Exception("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
        }
        return imagePDFName + "\\" + imagePDFName + "_1.png";
    }

    public static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

}